'use strict';
import Base from './base.js';
export default class extends Base {

	async backcardlistAction(){
		let page = JSON.parse(this.post('page'))
		let shopid = this.shop_userinfo.departmentid;
		let where = {
			'b.departmentid':shopid,
			'b.status':page.zt>0?['IN','1,2']:page.zt,
			'b.remarks|g.vipcard|a.name|g.name':['like','%'+page.search+'%']
		}

		if (page.times && (page.times[0] != null && page.times[1] != null)) {
			let begintime = Math.floor(new Date(page.times[0]).setHours(0,0,0,0)/1000)
			let endtime = Math.floor(new Date(page.times[1]).setHours(0,0,0,0)/1000) + 86400
			where['b.addtime'] = {'>=': begintime, '<': endtime}
 		}


		let data = await this.model('or_shop_backcardorder')
				.alias('b')
				.field('b.id, b.order_sn, b.ordertype, b.status, b.addtime, b.money, IF(b.remarks!="",b.remarks,"无") as remarks,b.isstore,a.name as aname,g.name as gname,g.vipcard, g.id as gid,s.name as sname')
				.join('`think_or_guest` g on g.id=b.guestid')
				.join('`think_or_admin` a on a.id=b.operatorid')
				.join('`think_or_admin` s on s.id=b.auditorid')
				.page(page.pages, page.limits)
				.where(where)
				.order('b.id DESC')
				.countSelect();
		return this.json(data);
	}

	// 客户退卡业务
	async backcardsAction(){
		let data = JSON.parse(this.post('data'));

		let shopid = this.shop_userinfo.departmentid;

		let addtime = Math.round(new Date().valueOf()/1000);

		let model = this.model('or_shop_backcardorder');

		let ordersn = await this.getordersn('TKD',1)

		await model.transaction(async () => {

			try {

				/*
				* 1、通过oids直接禁用客户赠送的产品和项目
				* 2、在联合qkid禁用客户要退的期卡，并取出卡id，用于添加退卡单详情
				* 3、禁用lcid里对应的疗程，并取出卡id，用于添加退卡详情
				* 4、添加退卡单，添加退卡单详情
				* 5、根据是否存入账户，更新客户余额信息(这一步在结账时做)
				*/
			
				let ginfo = data.ginfo, oids = data.oids, qkid = data.qkid, lcid = data.lcid, store = data.store, backmoney = data.backmoney, remarks = data.remarks;

				// 获取开卡时赠送的产品，如果存在则禁用
				let giftGoods = await this.model('or_shop_guest_temp_reserve').db(model.db())
						.where({shopid: shopid, isgift: 1, guestid: ginfo.id,  orderid: ['IN', oids]})
						.select();

				if (!think.isEmpty(giftGoods)) {
					let banGoods = await this.model('or_shop_guest_temp_reserve').db(model.db())
						.where({shopid: shopid, isgift: 1, guestid: ginfo.id, orderid: ['IN', oids]}).update({isdisabled: 1});

					if (!banGoods) {
						await model.rollback();
						return this.fail('禁用开卡赠送的产品失败');
					}
				}

				// 获取开卡是赠送的项目，如果存在则禁用
				let giftSubjects = await this.model('or_shop_guestcardsubject').db(model.db())
						.where({shopid: shopid, guestid: ginfo.id, discount: 0, orderid: ['IN', oids]})
						.select();

				if (!think.isEmpty(giftSubjects)) {
					let banSubjects = await this.model('or_shop_guestcardsubject').db(model.db())
							.where({shopid: shopid, guestid: ginfo.id, discount: 0, orderid: ['IN', oids]})
							.update({isdisabled: 1});
					if (!banSubjects) {
						await model.rollback();
						return this.fail('禁用开卡赠送的项目失败')
					}
				}

				// 如果qkid存在，则取出客户下面的期卡对应的guestcardsubject表的id（用于添加退卡详情）
				// 并禁用这些期卡
				let qksubs = [];
				if (!think.isEmpty(qkid)) {
					qksubs = await this.model('or_shop_guestcardsubject').db(model.db())
					.where({shopid: shopid, guestid: ginfo.id, orderid: ['IN', oids], cardid: ['IN', qkid]})
					.select();

					let banQks = await this.model('or_shop_guestcardsubject').db(model.db())
							.where({shopid: shopid, guestid: ginfo.id, orderid: ['IN', oids], cardid: ['IN', qkid]})
							.update({isdisabled: 1});

					if (!banQks) {
						await model.rollback();
						return this.fail('禁用客户期卡失败');
					}
				}

				// 如果lcid存在，则取出疗程卡id，并禁用当前疗程
				let lcsubs = [];
				if (!think.isEmpty(lcid)) {
					lcsubs = await this.model('or_shop_guestcardsubject').db(model.db())
					.where({id: ['IN', lcid]}).select();

					let banLcs = await this.model('or_shop_guestcardsubject').db(model.db())
							.where({id: ['IN', lcid]}).update({isdisabled: 1});
					if (!banLcs) {
						await model.rollback();
						return this.fail('禁用客户疗程失败');
					}
				}

				// 制作退卡单
				let addBackCards = {
					order_sn: ordersn,
					ordertype: 10,
					departmentid: shopid,
					guestid: data.ginfo.id,
					money: parseFloat(data.backmoney*1).toFixed(2),
					operatorid: this.shop_userinfo.id,
					remarks: data.remarks,
					addtime: addtime,
					isstore: store?1:0,
				}

				let orderid = await model.add(addBackCards);

				// 合并两次取出的卡项，并制作退卡详情
				let merge = lcsubs.concat(qksubs);
				
				if (!think.isEmpty(merge)) {
					let backCardsInfo = [];

					for (var i = merge.length - 1; i >= 0; i--) {
						backCardsInfo.push({
							orderid: orderid,
							cardid: merge[i].cardid,
							cardsubjectid: merge[i].id,
							addtime: addtime
						})
					}

					let addBackCardsInfo = await this.model('or_shop_backcardinfo').db(model.db()).addMany(backCardsInfo);

					if (!addBackCardsInfo) {
						await model.rollback();
						return this.fail('添加退卡详情记录失败');
					}
				}

				await model.commit();
				return this.success('退卡成功');
			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('退卡失败');
			}
		})
	}

	// 获取当前退卡待审核信息
	async getbackcardinfoAction(){
		let backid = this.post('id');

		let back = await this.model('or_shop_backcardorder')
				.alias('bo')
				.field('bo.*,g.name')
				.join('`think_or_guest` g on g.id=bo.guestid')
				.where({'bo.id':backid})
				.find();

		let backinfo = [];
		if (back.ordertype === 10) {
			backinfo = await this.model('or_shop_backcardinfo')
					.alias('bi')
					.field('gc.cardtype, s.name, gc.isdisabled')
					.join('`think_or_shop_guestcardsubject` gc on gc.id=bi.cardsubjectid')
					.join('`think_or_subject` s on s.id=gc.subjectid')
					.where({'bi.orderid': backid})
					.select();
		}
		

		let data = {
			back: back,
			backinfo: backinfo,
		}

		return this.json(data);
	}

	// 退卡审核
	async checkbackcardAction(){
		let data = JSON.parse(this.post('data'));

		let orderid = data.bid, alist = data.alist, ulist = data.ulist;

		let shopid = this.shop_userinfo.departmentid;

		let aid = this.shop_userinfo.id;

		let addtime = Math.round(new Date().valueOf()/1000);

		let model = this.model('or_shop_backcardorder');

		await model.transaction(async ()=>{

			try {
				
				/*
				1、首先取出当前订单，判断是退卡还是退款
				2、根据不同订单类型，制作不同数据
					-> 如果为退卡，则判断是否为退款转余额
					-> 如果为退款转余额，则不添加任何业绩，直接结账，并且把金额写入到账户日志，然后增加账户余额。
					-> 如果仅退款，则扣除添加的账户余额，并且添加余额出款日志。并制作并添加扣除业绩人员。（写如两个表） 
					-> 如果为退款，则和上面仅退款一样。
				3、最后更改当前订单状态（如果为转卡则状态为已分配）
				*/

				let oInfo = await model.where({id: orderid}).find();

				// 先制作退款单，ordertype === 11
				if (oInfo.ordertype%2) {

					let addUsers = [], addAccountLog = [], addYeJiTiCheng = [];

					for (var i = alist.length - 1; i >= 0; i--) {
						let increAcc = await this.model('or_shop_account').db(model.db()).where({id: alist[i].id}).decrement('balance', alist[i].paymoney);

						if (!increAcc) {
							await model.rollback();
							return this.fail('出款账户错误');
						}

						addAccountLog.push({
							departmentid: shopid,
							type: 2,
							accountid: alist[i].id,
							ordertype: 'TQD',
							orderid: orderid,
							money: -alist[i].paymoney,
							addtime: oInfo.addtime
						})
					}

					if (!think.isEmpty(addAccountLog)) {
						let accLog = await this.model('or_shop_accountlog').db(model.db()).addMany(addAccountLog);

						if (!accLog) {
							await model.rollback();
							return this.fail('添加出款账户记录失败');
						}
					}

					for (var i = ulist.length - 1; i >= 0; i--) {
						addUsers.push({
							orderid: orderid,
							feattype: 'TQD',
							shopid: shopid,
							feat: -ulist[i].feat,
							bumenid: ulist[i].bumenid,
							xiaozuid: ulist[i].xiaozuid,
							userid: ulist[i].id,
							addtime: oInfo.addtime
						})

						addYeJiTiCheng.push({
							shopid: shopid,
							orderid: orderid,
							ordertype: 'TQD',
							xianjinyeji: -ulist[i].feat,
							userid: ulist[i].id,
							bumenid: ulist[i].bumenid,
							xiaozuid: ulist[i].xiaozuid,
							addtime: oInfo.addtime,
							guestid: oInfo.guestid
						})
					}

					if (!think.isEmpty(addUsers)) {
						let yejiLog = await this.model('or_shop_yejixianjin').db(model.db()).addMany(addUsers);

						let otherLog = await this.model('or_shop_yejiticheng').db(model.db()).addMany(addYeJiTiCheng);

						if (!yejiLog && !otherLog) {
							await model.rollback();
							return this.fail('业绩扣除失败');
						}
					}

					let finish = await model.where({id: orderid}).update({status: 1, auditorid: aid});

					if (finish) {
						await model.commit();
						return this.success('退款成功');
					} else {
						await model.rollback();
						return this.fail('退款失败');
					}

				} else {

					// 判断是否为转卡，并且根据isstore处理数据
					if (oInfo.isstore) {
						let guestAccountLog = {
							guestid: oInfo.guestid,
							shopid: shopid,
							ordertype: 'CZD',
							orderid: orderid,
							balance: oInfo.money,
							addtime: oInfo.addtime,
							type: 5
						}

						let addGuestAccountLog = await this.model('or_shop_guest_accountlog').db(model.db()).add(guestAccountLog);

						let increBalance = await this.model('or_guest').db(model.db()).where({id: oInfo.guestid}).increment('balance', oInfo.money);

						let finish = await model.where({id: orderid}).update({status: 2, auditorid: aid});

						if (!addGuestAccountLog && !increBalance && !finish) {
							await model.rollback();
							return this.fail('转至余额失败');
						} else {
							await model.commit();
							return this.success('转至余额成功');
						}

					} else {
						let addUsers = [], addAccountLog = [], addYeJiTiCheng = [];

						for (var i = alist.length - 1; i >= 0; i--) {
							let increAcc = await this.model('or_shop_account').db(model.db()).where({id: alist[i].id}).decrement('balance',alist[i].paymoney);

							if (!increAcc) {
								await model.rollback();
								return this.fail('出款账户错误');
							}

							addAccountLog.push({
								departmentid: shopid,
								type: 2,
								accountid: alist[i].id,
								ordertype: 'TKD',
								orderid: orderid,
								money: -alist[i].paymoney,
								addtime: oInfo.addtime
							})
						}

						if (!think.isEmpty(addAccountLog)) {
							let accLog = await this.model('or_shop_accountlog').db(model.db()).addMany(addAccountLog);

							if (!accLog) {
								await model.rollback();
								return this.fail('添加出款账户记录失败');
							}
						}

						for (var i = ulist.length - 1; i >= 0; i--) {
							addUsers.push({
								orderid: orderid,
								feattype: 'TKD',
								shopid: shopid,
								feat: -ulist[i].feat,
								bumenid: ulist[i].bumenid,
								xiaozuid: ulist[i].xiaozuid,
								userid: ulist[i].id,
								addtime: oInfo.addtime
							})

							addYeJiTiCheng.push({
								shopid: shopid,
								orderid: orderid,
								ordertype: 'TKD',
								xianjinyeji: -ulist[i].feat,
								userid: ulist[i].id,
								bumenid: ulist[i].bumenid,
								xiaozuid: ulist[i].xiaozuid,
								addtime: oInfo.addtime,
								guestid: oInfo.guestid
							})
						}

						if (!think.isEmpty(addUsers)) {
							let yejiLog = await this.model('or_shop_yejixianjin').db(model.db()).addMany(addUsers);

							let otherLog = await this.model('or_shop_yejiticheng').db(model.db()).addMany(addYeJiTiCheng);

							if (!yejiLog && !otherLog) {
								await model.rollback();
								return this.fail('业绩扣除失败');
							}
						}

						let finish = await model.where({id: orderid}).update({status: 1, auditorid: aid});

						if (finish) {
							await model.commit();
							return this.success('退款成功');
						} else {
							await model.rollback();
							return this.fail('退款失败');
						}
					}

				}

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('退卡审核失败');
			}
		})
	}

	// 删除当前退卡单
	async deletebackcardAction(){
		let orderid = this.post('id');

		let shopid = this.shop_userinfo.departmentid;

		let model = this.model('or_shop_backcardorder');

		await model.transaction(async ()=>{

			try {

				/*
				* 1、先获取退卡详情单信息
				* 2、在通过获取的退单信息把客户的卡项还原
				* 3、再根据orderid把客户开卡时赠送的品项还原
				* 4、删除当前退卡单和退卡详情单
				*/

				let olist = await this.model('or_shop_backcardinfo').db(model.db())
						.alias('i')
						.field('s.orderid, s.id')
						.join('`think_or_shop_guestcardsubject` s on s.id=i.cardsubjectid')
						.where({'i.orderid': orderid})
						.select();

				let oinfo = await model.where({id: orderid}).find();

				if (!think.isEmpty(olist)) {
					let oids = [], subids = [];
					for (var i = olist.length - 1; i >= 0; i--) {
						if (oids.indexOf(olist[i].orderid) === -1) {
							oids.push(olist[i].orderid)
						}
						if (subids.indexOf(olist[i].id) === -1) {
							subids.push(olist[i].id)
						}
					}

					// 先还原卡项
					let restoreCards = await this.model('or_shop_guestcardsubject').db(model.db())
							.where({id: ['IN', subids]}).update({isdisabled: 0});

					if (!restoreCards) {
						await model.rollback();
						return this.fail('还原客户卡项失败');
					}

					// 如果存在，则还原赠送的项目
					oids = oids.length?oids:0;
					let existSubjects = await this.model('or_shop_guestcardsubject').db(model.db())
							.where({shopid: shopid, guestid: oinfo.guestid, orderid: ['IN', oids], discount: 0})
							.select();

					if (!think.isEmpty(existSubjects)) {
						let restoreSubjects = await this.model('or_shop_guestcardsubject').db(model.db())
								.where({shopid: shopid, guestid: oinfo.guestid, orderid: ['IN', oids], discount: 0})
								.update({isdisabled: 0});

						if (!restoreSubjects) {
							await model.rollback();
							return this.fail('还原赠送项目失败');
						}
					}

					// 如果存在，则还原赠送的产品
					let existGoods = await this.model('or_shop_guest_temp_reserve').db(model.db())
							.where({shopid: shopid, guestid: oinfo.guestid, orderid: ['IN', oids], isgift: 1})
							.select();

					if (!think.isEmpty(existGoods)) {
						let restoreGoods = await this.model('or_shop_guest_temp_reserve').db(model.db())
							.where({shopid: shopid, guestid: oinfo.guestid, orderid: ['IN', oids], isgift: 1})
							.update({isdisabled: 0});

						if (!restoreGoods) {
							await model.rollback();
							return this.fail('还原赠送的产品失败');
						}
					}
				}

				// 处理完客户卡项和赠送后删除当前订单
				let delOrderInfo = await this.model('or_shop_backcardinfo').db(model.db()).where({orderid: orderid}).delete();

				let delOrder = await model.where({id: orderid}).delete();

				if (!delOrderInfo && !delOrder) {
					await model.rollback();
					return this.fail('删除订单详情失败');
				}

				await model.commit();
				return this.success('删除成功');

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('删除失败');
			}
		})
	}

	// 获取当前客户余额使用情况
	async getrechargeinfoAction(){

		let page = this.post();

		let pages = page.pages;

		let limits = page.limits;

		let gid = page.gid;

		let shopid = this.shop_userinfo.departmentid;

		let data = await this.model('or_shop_guest_accountlog')
				.where({guestid: gid, shopid: shopid})
				.page(pages, limits)
				.order('id DESC')
				.countSelect();

		return this.json(data);
	}

	// 开退款单
	async backaccountAction(){

		let data = this.post();

		let shopid = this.shop_userinfo.departmentid;

		let adminid = this.shop_userinfo.id;

		let addtime = Math.round(new Date().valueOf()/1000);

		let model = this.model('or_shop_backcardorder');

		let ordersn = await this.getordersn('TQD',1)

		await model.transaction(async ()=>{

			try {

				/*
				1、制作退款单
				2、制作退款单附表
				3、记录客户账户退款日志
				4、客户账户余额减去
				*/

				let makeOrder = {
					order_sn: ordersn,
					ordertype: 11,
					departmentid: shopid,
					guestid: data.gid,
					money: data.backmoney,
					operatorid: adminid,
					remarks: data.remarks,
					addtime: addtime
				}

				let orderid = await model.add(makeOrder);

				let makeOrderInfo = {
					orderid: orderid,
					cardid: data.gid,
					addtime: addtime,
					type: 1
				}

				let addOrderInfo = await this.model('or_shop_backcardinfo').db(model.db()).add(makeOrderInfo);

				let makeAccountLog = {
					guestid: data.gid,
					shopid: shopid,
					ordertype: 'TQD',
					orderid: orderid,
					balance: -data.backmoney,
					addtime: addtime,
					type: 4
				}

				let addAccountLog = await this.model('or_shop_guest_accountlog').db(model.db()).add(makeAccountLog);

				let updateAccount = await this.model('or_guest').db(model.db()).where({id: data.gid}).decrement('balance', data.backmoney*1);

				if (!orderid && !addOrderInfo && !addAccountLog && !updateAccount) {
					await model.rollback();
					return this.fail('退款失败');
				}

				await model.commit();
				return this.success('退款成功');

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('退款失败');
			}
		})
	}

	// 删除当前退款单
	async deletebackaccountAction(){

		let orderid = this.post('id');

		let shopid = this.shop_userinfo.departmentid;

		let model = this.model('or_shop_backcardorder');

		await model.transaction(async ()=>{

			try {

				/*
				* 1、先获取账户日志信息
				* 2、把减去的余额增加回去
				* 3、删除退款单和退款附表信息
				*/

				let gaccolog = await this.model('or_shop_guest_accountlog')
				.db(model.db())
				.where({type:4, orderid: orderid, shopid: shopid, ordertype: 'TQD'})
				.find();

				let zzguest = await this.model('or_guest').db(model.db()).where({id: gaccolog.guestid}).increment('balance', -gaccolog.balance);

				let delbacklog = await this.model('or_shop_backcardinfo').db(model.db()).where({orderid: orderid}).delete();

				let delgaccolog = await this.model('or_shop_guest_accountlog').db(model.db()).where({type:4, orderid: orderid, shopid: shopid, ordertype: 'TQD'}).delete();

				let delback = await model.where({id: orderid}).delete();

				if (zzguest && delbacklog && delback && delgaccolog) {
					await model.commit();
					return this.success('删除退款成功');
				} else {
					await model.rollback();
					return this.fail('删除退款单失败');
				}

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('删除退款失败');
			}
		})
	}

	// 查看客户退款、退卡信息
	async lookinfoAction(){
		let orderid = this.post('id');

		let shopid = this.shop_userinfo.departmentid;
		let oInfo = await this.model('or_shop_backcardorder')
				.alias('o')
				.field('o.*, g.name')
				.join('`think_or_guest` g on g.id=o.guestid')
				.where({'o.id': orderid})
				.find();

		let sLogs = [], aLogs = [], uList = [];

		if (!oInfo.isstore) {
			sLogs = await this.model('or_shop_backcardinfo')
			.alias('i')
			.field('s.name,g.cardtype')
			.join('`think_or_shop_guestcardsubject` g on g.id=i.cardsubjectid')
			.join('`think_or_subject` s on s.id=g.subjectid')
			.where({'i.orderid': orderid})
			.select();

			aLogs = await this.model('or_shop_accountlog')
			.alias('l')
			.field('l.money, a.name, a.accountsn')
			.join('`think_or_shop_account` a on a.id=l.accountid')
			.where({'l.departmentid': shopid, 'l.type': 2, 'l.ordertype':['IN', ['TKD','TQD']], 'l.orderid': orderid})
			.select();

			uList = await this.model('or_shop_yejiticheng')
			.alias('y')
			.field('y.id,y.xianjinyeji as money,y.userid,y.bumenid,y.xiaozuid, u.name, u.worknum')
			.join('`think_or_app_user` u on u.id=y.userid')
			.where({'y.shopid': shopid, 'y.ordertype': ['IN', ['TKD','TQD']], 'y.orderid': orderid})
			.select();
		}

		let data = {
			oinfo: oInfo,
			slogs: sLogs,
			alogs: aLogs,
			ulist: uList
		}

		return this.json(data);
	}

	async getbackcardyejiAction () {
		let orderid = this.post('orderid')

		let list = await this.model('or_shop_yejixianjin')
		.alias('y')
		.field('y.*, u.name')
		.join('`think_or_app_user` u on y.userid=u.id')
		.where({'y.feattype': ['IN', ['TKD','TQD']], 'y.orderid': orderid})
		.select()

		return this.json(list)
	}

	// 获取已经分配的业绩提成信息
	async yejitichentlistAction(){
		let orderid = this.post('orderid');

		let ulist = await this.model('or_shop_fenpeiticheng')
				.alias('bs')
				.field('bs.*, u.name')
				.join('`think_or_app_user` u on u.id=bs.userid')
				.where({'bs.ordertype': ['IN',[10,11]], 'bs.orderid': orderid})
				.select();

		return this.json(ulist);
	}

	async queryguestsAction(){
		let query = this.get('query');
		let shopid = this.shop_userinfo.departmentid;

		let list = await this.model('or_guest')
				.field('id,name,vipcard,phone,sex,level,balance,giftbalance')
				.where({departmentid: shopid, 'name|vipcard|phone': ['LIKE', '%'+query+'%'], initial_info: 1})
				.select();

		return this.json(list);
	}

	async guestcardlistAction(){
		let gid = this.get('id');
		let shopid = this.shop_userinfo.departmentid;
		let endtime = Math.round(new Date().valueOf()/1000);

		// 客户期卡
		let qlist = await this.model('or_shop_guestcardsubject')
				.alias('g')
				.field('g.id, g.cardid, c.price, c.number, c.name, g.orderid, g.endtime, count(g.id) as geshu')
				.join('`think_or_shop_card` c on c.id=g.cardid')
				.where('g.shopid='+shopid+' AND g.guestid='+gid+' AND g.cardtype=1 AND g.endtime>'+endtime+' AND g.isdisabled=0')
				.group('g.cardid')
				.select();

		// 客户疗程卡，单个项目列表
		let clist = await this.model('or_shop_guestcardsubject')
				.alias('g')
				.field('g.id, g.subjectid, g.price, g.disprice, s.name, g.orderid, g.num, g.nownum')
				.join('`think_or_subject` s on s.id=g.subjectid')
				.where('g.shopid='+shopid+' AND  g.guestid='+gid+' AND g.cardtype=2 AND g.discount!=0 AND g.nownum>0 AND g.isdisabled=0')
				.select();

		let data = {
			qlist: qlist,
			clist: clist
		}

		return this.json(data);
	}

	async getreducelogAction(){

		let oids = JSON.parse(this.post('oid'));

		if (think.isEmpty(oids)) {
			oids = [0];
		}

		let shopid = this.shop_userinfo.departmentid;

		let rds_subs = await this.model('or_shop_guestcardsubject')
				.alias('g')
				.field('g.id, s.name, g.price, g.num, g.nownum')
				.join('`think_or_subject` s on s.id=g.subjectid')
				.where({'g.shopid': shopid, 'g.orderid': ['IN', oids], 'g.isgift': 1})
				.select()

		// 通过orderid获取赠送的品项，并显示赠送的消费记录
		let rds_gods = await this.model('or_shop_guest_temp_reserve')
				.alias('r')
				.field('r.id, r.num, r.nownum, r.price, g.name')
				.join('`think_or_goods` g on g.id=r.goodsid')
				.where({'r.shopid': shopid, 'r.orderid': ['IN', oids], 'r.isgift': 1})
				.select();

		let rds = {
			rsubs: rds_subs,
			rgods: rds_gods
		}

		return this.json(rds);
	}

	// 退卡、退款反审核
	async againstcheckAction(){

		let oid = this.get('id');

		let shopid = this.shop_userinfo.departmentid;

		let oInfo = await this.model('or_shop_backcardorder').where({id: oid}).find();

		if (oInfo.status === 2 && oInfo.isstore === 0) {
			return this.fail('当前订单已分配工资，不能反审核');
		}

		let model = this.model('or_shop_backcardorder');

		await model.transaction(async ()=>{
			try {

				if (oInfo.isstore) {
					let accountLog = await this.model('or_shop_guest_accountlog').db(model.db()).where({shopid: shopid, type: 5, orderid: oid}).find();

					let decreBalance = await this.model('or_guest').db(model.db()).where({id: oInfo.guestid}).decrement('balance', accountLog.balance);

					let delAccountLog = await this.model('or_shop_guest_accountlog').db(model.db()).where({shopid: shopid, type: 5, orderid: oid}).delete();

					if (accountLog && decreBalance && delAccountLog) {
						await model.commit();
						return this.success('反审核成功');
					} else {
						await model.rollback();
						return this.fail('反审核失败');
					}
				} else {

					let accLog = await this.model('or_shop_accountlog').db(model.db()).where({departmentid: shopid, type: 2, ordertype: ['IN', ['TKD','TQD']], orderid: oid}).select();

					for (var i = accLog.length - 1; i >= 0; i--) {
						let decreAcc = await this.model('or_shop_account').db(model.db()).where({id: accLog[i].accountid}).increment('balance', -accLog[i].money);
						if (!decreAcc) {
							await model.rollback();
							return this.fail('退回金额失败');
						}
					}

					let delAccLog = await this.model('or_shop_accountlog').db(model.db()).where({departmentid: shopid, type: 2, ordertype: ['IN', ['TKD','TQD']], orderid: oid}).delete();

					if (!delAccLog) {
						await model.rollback();
						return this.fail('删除出款记录失败');
					}

					let delYejiLog = await this.model('or_shop_yejixianjin').db(model.db()).where({shopid: shopid, feattype: ['IN', ['TKD', 'TQD']], orderid: oid}).delete();

					let delXjLog = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: oid, ordertype: ['IN', ['TKD', 'TQD']]}).delete();

					if (!delYejiLog && !delXjLog) {
						await model.rollback();
						return this.fail('删除扣款业绩失败');
					}

					let backOrderStatus = await model.where({id: oid}).update({status: 0, auditorid: 0});

					if (backOrderStatus) {
						await model.commit();
						return this.success('反审核成功');
					} else {
						await model.rollback();
						return this.fail('反审核失败');
					}

				}

			} catch (e) {
				console.log(e);
				await model.rollback();
				return this.fail('反审核失败');
			}
		})
	}

	// 重新分配已审核退卡/退款业绩
	async againallotAction(){

		/*
		 * 1、同时写入or_shop_yejixianjin和or_shop_yejiticheng两张表
		 * 2、首先，同时删除这两张表的业绩
		 * 3、然后，同时把修改的业绩添加到这两张表
		 */

		let data = JSON.parse(this.post('data'));

		let oid = data.oid, ulist = data.user, type = data.ordertype;

		let shopid = this.shop_userinfo.departmentid;

		let addtime = Math.round(new Date().valueOf()/1000);

		let oInfo = await this.model('or_shop_backcardorder').where({id: oid}).find();

		let addXian = [], addCheng = [];

		for (var i = ulist.length - 1; i >= 0; i--) {

			addXian.push({
				orderid: oid,
				feattype: (type==10?'TKD':'TQD'),
				shopid: shopid,
				feat: ulist[i].feat,
				bumenid: ulist[i].bumenid,
				xiaozuid: ulist[i].xiaozuid,
				userid: ulist[i].userid,
				addtime: oInfo.addtime
			})

			addCheng.push({
				shopid: shopid,
				orderid: oid,
				ordertype: (type==10?'TKD':'TQD'),
				xianjinyeji: ulist[i].feat,
				userid: ulist[i].userid,
				bumenid: ulist[i].bumenid,
				xiaozuid: ulist[i].xiaozuid,
				addtime: oInfo.addtime,
				guestid: oInfo.guestid
			})

		}

		let model = this.model('or_shop_yejiticheng');

		await model.transaction(async ()=>{
			try {
			let tcRes = await model.where({shopid: shopid, orderid: oid, ordertype: ['IN', ['TQD','TKD']]}).select();

			let xjRes = await this.model('or_shop_yejixianjin').db(model.db()).where({shopid: shopid, feattype: ['IN', ['TQD','TKD']], orderid: oid}).select();

			if (tcRes.length && xjRes.length) {
				let delTcRes = await model.where({shopid: shopid, orderid: oid, ordertype: ['IN', ['TQD','TKD']]}).delete();

				let delXjRes = await this.model('or_shop_yejixianjin').db(model.db()).where({shopid: shopid, feattype: ['IN', ['TQD','TKD']], orderid: oid}).delete();

				if (!delTcRes && !delXjRes) {
					await model.rollback();
					return this.fail('删除现金业绩失败');
				}
			}

			if (addXian.length && addCheng.length) {
				let addTcRes = await model.addMany(addCheng);

				let addXjRes = await this.model('or_shop_yejixianjin').db(model.db()).addMany(addXian);

				if (!addTcRes && !addXjRes) {
					await model.rollback();
					return this.fail('重新分配业绩失败')
				}
			}

			await model.commit();
			return this.success('重新分配业绩成功');
			} catch(e){
				await model.rollback();
				return this.fail('重新分配业绩失败')
			}

		})
	}

}